package wens.pig.base.plugin.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.eclipse.jetty.util.StringUtil;

/**
 * 校验名称
 * @author xn-lijunjie
 * @since 2022年07月31日-16:12
 */
public class CheckNameFormPlugin extends AbstractOperationServicePlugIn {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        e.getFieldKeys().add("name");
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        for (DynamicObject dataEntity : e.getDataEntities()) {
            String name = dataEntity.getString("name");
            if(StringUtil.isNotBlank(name)){
                QFilter qFilter = new QFilter("name", QCP.equals, name);
                qFilter.and("id",QCP.not_equals,dataEntity.getPkValue());
                DynamicObject[] names = BusinessDataServiceHelper.load(dataEntity.getDynamicObjectType().getName(), "name",
                        qFilter.toArray());
                if (names.length > 0) {
                    e.setCancel(true);
                    e.setCancelMessage(String.format("该<%s>的名称已存在", dataEntity.getDynamicObjectType().getDisplayName().getLocaleValue()));
                    return;
                }
            }
        }
    }
}
